package com.person.news.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.struts2.ServletActionContext;

import com.googlecode.jsonplugin.annotations.JSON;
import com.person.base.model.BaseUser;
import com.person.commons.struts2.BaseAction;
import com.person.commons.utils.Constants;
import com.person.commons.utils.FlipPageInfo;
import com.person.dic.model.Dic;
import com.person.news.model.News;
import com.person.news.model.NewsAnnex;
import com.person.news.service.NewsService;
import com.person.title.model.TitleFunc;

public class NewsAction extends BaseAction {

	private File[] annex1; // 中文
	private String[] annex1ContentType;
	private String[] annex1FileName;
	private File[] annex2; // 英文
	private String[] annex2ContentType;
	private String[] annex2FileName;
	private File[] annex3; // 中英文
	private String[] annex3ContentType;
	private String[] annex3FileName;
	private String savePath;
	private News news;
	private List<NewsAnnex> newsAnnex;

	private NewsService newsService;

	private String imagevideo;
	private String imagevideoFileName;
	private String imagevideoContentType;

	private FlipPageInfo fpi = new FlipPageInfo();
	private String newsId;
	private String download;

	private String[] ids;
	private String newsType;
	private String newsTitle;
	private String userDate;
	private String newsContent;
	private String newsTypeName;

	private String str;
	private TitleFunc titleFunc;
	private List<Dic> dicList;

	public String index() {
		
		return "createNew";
	}

	/**
	 * 上传文件
	 * 
	 * @param savePath
	 *            文件保存根目录
	 * @return
	 * @throws BaseException
	 *             抛出异常表示文件上传失败
	 */
	public String[][] uploadAndSave(File[] annex, String[] annexFileName,
			String[] annexContentType, String date) throws Exception {
		String[][] result = new String[0][0];
		savePath = request.getRealPath(File.separator) + Constants.ANNEX_DIR;
		try {
			if (annex != null) {
				File file = new File(savePath);
				if (!file.exists()) {
					file.mkdirs();
				}
				result = new String[annex.length][4]; // 数组值：0文件原名，1文件保存在服务器上的名称，2文件大小，3文件类型
				FileOutputStream out = null;
				FileInputStream in = null;
				byte[] buff = new byte[1024];
				String fileType;
				String saveName;
				int length = 0;
				for (int i = 0; i < annex.length; i++) {
					if (annexFileName[i].indexOf(".") != -1) {
						fileType = annexFileName[i].substring(annexFileName[i]
								.lastIndexOf(".") + 1);
					} else {
						fileType = "";
					}
					saveName = date + i + "." + fileType;
					out = new FileOutputStream(savePath + File.separator
							+ saveName);
					in = new FileInputStream(annex[i]);
					if (in != null) {
						// 排除上传的文件为新建、大小为0的文件
						while ((length = in.read(buff)) > 0) {
							out.write(buff, 0, length);
						}
						result[i][0] = annexFileName[i]; // 真实的附件名称
						result[i][1] = saveName; // 服务器上面保存的名称
						result[i][2] = "" + (annex[i].length()); // 附件大小
						result[i][3] = fileType; // 附件类型
						in.close();
						out.close();
					}
				}
			}
		} catch (Exception e) {
			throw new Exception();
		}
		return result;
	}

	public String upload() {
		String imagevideoType = getImagevideoFileName().substring(
				getImagevideoFileName().lastIndexOf("."));
		String rootDir = request.getRealPath(File.separator)
				+ Constants.NEWS_DIR;
		String newsTypeName = String.valueOf(new Date().getTime());
		String imagevideoDir = rootDir + newsTypeName + imagevideoType;

		File rootFile = new File(rootDir);
		File imagevideoFile = new File(imagevideoDir);
		if (!rootFile.exists()) {
			rootFile.mkdirs();
		}

		if (imagevideoFile.exists()) {
			imagevideoFile.delete();
		}

		try {
			FileInputStream is = new FileInputStream(imagevideo);
			FileOutputStream os = new FileOutputStream(imagevideoDir);
			byte[] buffer = new byte[1024];
			int lenth = 0;
			while ((lenth = is.read(buffer)) > 0) {
				os.write(buffer);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		news.setNewsTypeName(newsTypeName + imagevideoType);
		return imagevideoDir;
	}

	public String create() throws Exception {
		// 获得登录用户的身份
		BaseUser user = (BaseUser) request.getSession().getAttribute(
				Constants.SESSION_USER);
		if (imagevideo != null) {
			upload();
		}
		news.setUserId(user.getUserId());
		news.setUserDate(new Date());
		news.setNewsClick(0);
		String id = newsService.createNews(news);
		String[][] result;
		try {
			if (annex1 != null && annex1.length != 0) {
				String date = new Date().getTime() + "0";
				result = uploadAndSave(annex1, annex1FileName,
						annex1ContentType, date);
				for (int i = 0; i < result.length; i++) {
					NewsAnnex newsAnnex = new NewsAnnex();
					newsAnnex.setAneexFlag("0");
					newsAnnex.setAnnexName(result[i][0]);
					newsAnnex.setAnnexAlias(result[i][1]);
					newsAnnex.setAnnexSize(result[i][2]);
					newsAnnex.setNewsId(id);
					newsService.createNewsAnnex(newsAnnex);
				}
			}
			if (annex2 != null && annex2.length != 0) {
				String date = new Date().getTime() + "1";
				result = uploadAndSave(annex2, annex2FileName,
						annex2ContentType, date);
				for (int i = 0; i < result.length; i++) {
					NewsAnnex newsAnnex = new NewsAnnex();
					newsAnnex.setAneexFlag("1");
					newsAnnex.setAnnexName(result[i][0]);
					newsAnnex.setAnnexAlias(result[i][1]);
					newsAnnex.setAnnexSize(result[i][2]);
					newsAnnex.setNewsId(id);
					newsService.createNewsAnnex(newsAnnex);
				}
			}
			if (annex3 != null && annex3.length != 0) {
				String date = new Date().getTime() + "2";
				result = uploadAndSave(annex3, annex3FileName,
						annex3ContentType, date);
				for (int i = 0; i < result.length; i++) {
					NewsAnnex newsAnnex = new NewsAnnex();
					newsAnnex.setAneexFlag("2");
					newsAnnex.setAnnexName(result[i][0]);
					newsAnnex.setAnnexAlias(result[i][1]);
					newsAnnex.setAnnexSize(result[i][2]);
					newsAnnex.setNewsId(id);
					newsService.createNewsAnnex(newsAnnex);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return list();
	}

	public String list() {
		fpi = newsService.findAllNews(fpi);
		return "list";
	}

	public String detail() {
		news = newsService.findNewsById(newsId);
		newsAnnex = newsService.findAnnexByNewsId(newsId);
		titleFunc = newsService.findTitleFuncByFuncId(news.getFuncId());
		return "detail";
	}

	public String download() {

		return "down";
	}

	@SuppressWarnings("deprecation")
	public String delete() {
		news = newsService.findNewsById(newsId);
		String filePathAndName=request.getRealPath(File.separator)+Constants.NEWS_DIR+
			news.getNewsTypeName();
		delFile(filePathAndName);
		newsService.deleteNewsById(newsId);
		return list();
	}

	public String modifyIndex() {
		news = newsService.findNewsById(newsId);
		newsAnnex = newsService.findAnnexByNewsId(newsId);
		titleFunc=newsService.findTitleFuncByFuncId(news.getFuncId());
		return "modify";
	}

	public String modify() {
		if (newsType == "1" && news.getNewsType() != "1") {
			File delete = new File(request.getRealPath(File.separator)
					+ Constants.NEWS_DIR + news.getNewsTypeName());
			if (delete.exists()) {
				delete.delete();
			}
		}
		if (newsType == "2" && news.getNewsType() != "2") {
			File delete = new File(request.getRealPath(File.separator)
					+ Constants.NEWS_DIR + news.getNewsTypeName());
			if (delete.exists()) {
				delete.delete();
			}
		}
		newsService.deleteNewsAnnex(ids);
		String id = news.getNewsId();
		if (imagevideo != null) {
			String filePathAndName=request.getRealPath(File.separator)+Constants.NEWS_DIR+
			news.getNewsTypeName();
			delFile(filePathAndName);
			upload();
		}
		// news.setUserDate(new Date());

		// newsService.modifyNews("update News set
		// funcId=?,newsType=?,newsTitle=?,newsTitleEn=?,newsContent=?,newsContenEn=?,newsTypeName=?
		// where newsId=?",new
		// Object[]{news.getFuncId(),news.getNewsType(),news.getNewsTitle(),news.getNewsTitleEn(),news.get);
//		if(news.getNewsTitle().equals("")){
//			info = "新闻标题不能为空";
//			newsId = news.getNewsId();
//			return modifyIndex();
//		}
//		String reg = "[\\u4e00-\\u9fa5A-Za-z0-9\\.:\"\'()]";
//		Pattern p = Pattern.compile(reg);
//		Matcher m = p.matcher(news.getNewsTitle());
//		boolean r = m.find();
//		if(r == false){
//			info = "新闻标题不能含特殊字符";
//			newsId = news.getNewsId();
//			return modifyIndex();
//		}
		news.setUserDate(new Date());
		news.setUserId(((BaseUser) request.getSession().getAttribute(
				Constants.SESSION_USER)).getUserId());
		newsService.modifyNews(news);
		String[][] result;
		try {
			if (annex1 != null && annex1.length != 0) {
				String date = new Date().getTime() + "0";
				result = uploadAndSave(annex1, annex1FileName,
						annex1ContentType, date);
				for (int i = 0; i < result.length; i++) {
					NewsAnnex newsAnnex = new NewsAnnex();
					newsAnnex.setAneexFlag("0");
					newsAnnex.setAnnexName(result[i][0]);
					newsAnnex.setAnnexAlias(result[i][1]);
					newsAnnex.setAnnexSize(result[i][2]);
					newsAnnex.setNewsId(id);
					newsService.createNewsAnnex(newsAnnex);
				}
			}
			if (annex2 != null && annex2.length != 0) {
				String date = new Date().getTime() + "1";
				result = uploadAndSave(annex2, annex2FileName,
						annex2ContentType, date);
				for (int i = 0; i < result.length; i++) {
					NewsAnnex newsAnnex = new NewsAnnex();
					newsAnnex.setAneexFlag("1");
					newsAnnex.setAnnexName(result[i][0]);
					newsAnnex.setAnnexAlias(result[i][1]);
					newsAnnex.setAnnexSize(result[i][2]);
					newsAnnex.setNewsId(id);
					newsService.createNewsAnnex(newsAnnex);
				}
			}
			if (annex3 != null && annex3.length != 0) {
				String date = new Date().getTime() + "2";
				result = uploadAndSave(annex3, annex3FileName,
						annex3ContentType, date);
				for (int i = 0; i < result.length; i++) {
					NewsAnnex newsAnnex = new NewsAnnex();
					newsAnnex.setAneexFlag("2");
					newsAnnex.setAnnexName(result[i][0]);
					newsAnnex.setAnnexAlias(result[i][1]);
					newsAnnex.setAnnexSize(result[i][2]);
					newsAnnex.setNewsId(id);
					newsService.createNewsAnnex(newsAnnex);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list();
	}

	public String listByQualification() {
		StringBuffer hql = new StringBuffer(
				"select n.newsType,n.userDate,n.newsTitle,u.userName,n.newsId,n.newsFlag," +
						"n.newsTop,n.newsClick,t.funcName from News n,BaseUser u,TitleFunc t " +
						"where n.userId = u.userId and t.funcId=n.funcId ");
		if (!newsType.equals("3") && newsType.isEmpty() == false
				&& !newsType.equals("")) {
			hql.append(" and n.newsType='" + newsType + "'");
		}
		if (newsTitle.isEmpty() == false && !newsTitle.equals("")) {
			hql.append(" and n.newsTitle like'%" + newsTitle + "%'");
		}
		if (userDate.isEmpty() == false && !userDate.equals("")) {
			hql.append(" and DATE_FORMAT(n.userDate,'%Y-%m-%d')='" + userDate
					+ "'");
		}
		if(!news.getFuncId().isEmpty()&& !news.getFuncId().equals("")){
			hql.append(" and n.funcId ='"+news.getFuncId()+"'");
		}
//		if (newsContent.isEmpty() == false && !newsContent.equals("")) {
//			hql.append(" and n.newsContent like '%" + newsContent + "%'");
//		}
		hql.append(" order by n.funcId,n.newsType,n.userDate desc");
		fpi = newsService.findNewsByQualification(hql.toString(), fpi);
		return "listByQualification";
	}

	public InputStream getTargetFile() {
		return ServletActionContext.getServletContext().getResourceAsStream(
				Constants.ANNEX_DIR + download);
	}

	public String play() {
		return "play";
	}

	public String check() {
		 
			boolean b = newsService.findNewsByNewsTitle(news.getNewsTitle());
			if (b == true) {
				str = "1";
			} else if (b == false) {
				str = "2";
			} else {
				str = "3";
			}
		
		return "json";
	}
	 /**
	  * 删除在服务器上的文件
	  * @param filePathAndName
	  */
	public void delFile(String filePathAndName) { 
		
	     try { 
	       String filePath = filePathAndName; 
	       filePath = filePath.toString(); 
	       File myDelFile = new File(filePath); 
	       myDelFile.delete(); 
	     } 
	     catch (Exception e) { 
	       System.out.println("删除文件操作出错"); 
	       e.printStackTrace(); 
	     } 
	 } 
	public File[] getAnnex1() {
		return annex1;
	}

	public void setAnnex1(File[] annex1) {
		this.annex1 = annex1;
	}

	public String[] getAnnex1ContentType() {
		return annex1ContentType;
	}

	public void setAnnex1ContentType(String[] annex1ContentType) {
		this.annex1ContentType = annex1ContentType;
	}

	public String[] getAnnex1FileName() {
		return annex1FileName;
	}

	public void setAnnex1FileName(String[] annex1FileName) {
		this.annex1FileName = annex1FileName;
	}

	public File[] getAnnex2() {
		return annex2;
	}

	public void setAnnex2(File[] annex2) {
		this.annex2 = annex2;
	}

	public String[] getAnnex2ContentType() {
		return annex2ContentType;
	}

	public void setAnnex2ContentType(String[] annex2ContentType) {
		this.annex2ContentType = annex2ContentType;
	}

	public String[] getAnnex2FileName() {
		return annex2FileName;
	}

	public void setAnnex2FileName(String[] annex2FileName) {
		this.annex2FileName = annex2FileName;
	}

	public File[] getAnnex3() {
		return annex3;
	}

	public void setAnnex3(File[] annex3) {
		this.annex3 = annex3;
	}

	public String[] getAnnex3ContentType() {
		return annex3ContentType;
	}

	public void setAnnex3ContentType(String[] annex3ContentType) {
		this.annex3ContentType = annex3ContentType;
	}

	public String[] getAnnex3FileName() {
		return annex3FileName;
	}

	public void setAnnex3FileName(String[] annex3FileName) {
		this.annex3FileName = annex3FileName;
	}

	public News getNews() {
		return news;
	}

	public void setNews(News news) {
		this.news = news;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public void setNewsService(NewsService newsService) {
		this.newsService = newsService;
	}

	public String getImagevideo() {
		return imagevideo;
	}

	public void setImagevideo(String imagevideo) {
		this.imagevideo = imagevideo;
	}

	public String getImagevideoFileName() {
		return imagevideoFileName;
	}

	public void setImagevideoFileName(String imagevideoFileName) {
		this.imagevideoFileName = imagevideoFileName;
	}

	public String getImagevideoContentType() {
		return imagevideoContentType;
	}

	public void setImagevideoContentType(String imagevideoContentType) {
		this.imagevideoContentType = imagevideoContentType;
	}

	public FlipPageInfo getFpi() {
		return fpi;
	}

	public void setFpi(FlipPageInfo fpi) {
		this.fpi = fpi;
	}

	public String getNewsId() {
		return newsId;
	}

	public void setNewsId(String newsId) {
		this.newsId = newsId;
	}

	public List<NewsAnnex> getNewsAnnex() {
		return newsAnnex;
	}

	public void setNewsAnnex(List<NewsAnnex> newsAnnex) {
		this.newsAnnex = newsAnnex;
	}

	public String getDownload() {
		return download;
	}

	public void setDownload(String download) {
		this.download = download;
	}

	public String[] getIds() {
		return ids;
	}

	public void setIds(String[] ids) {
		this.ids = ids;
	}

	public String getNewsType() {
		return newsType;
	}

	public void setNewsType(String newsType) {
		this.newsType = newsType;
	}

	public String getNewsTitle() {
		return newsTitle;
	}

	public void setNewsTitle(String newsTitle) {
		this.newsTitle = newsTitle;
	}

	public String getUserDate() {
		return userDate;
	}

	public void setUserDate(String userDate) {
		this.userDate = userDate;
	}

	public String getNewsContent() {
		return newsContent;
	}

	public void setNewsContent(String newsContent) {
		this.newsContent = newsContent;
	}

	public String getNewsTypeName() {
		return newsTypeName;
	}

	public void setNewsTypeName(String newsTypeName) {
		this.newsTypeName = newsTypeName;
	}

	@JSON(name = "str")
	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}

	/**
	 * @return the titleFunc
	 */
	public TitleFunc getTitleFunc() {
		return titleFunc;
	}

	/**
	 * @param titleFunc the titleFunc to set
	 */
	public void setTitleFunc(TitleFunc titleFunc) {
		this.titleFunc = titleFunc;
	}

	public List<Dic> getDicList() {
		return dicList;
	}

	public void setDicList(List<Dic> dicList) {
		this.dicList = dicList;
	}


}
